package com.angel.core.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @ClassName: JsonUtil
 * @Description: json处理类
 * @author Liucx
 * @date 2014-4-24 下午4:43:04
 * 
 * @tag v1.0
 */
public class JsonUtil {

	private static final Gson gson = new Gson();
	private static final String RSPCODE = "rspcode";

	private JsonUtil() {
	}

	public static String toJson(Object object) {
		return gson.toJson(object);
	}

	public static String toJson(Object object, String timeType) {
		if (null == timeType || "".equals(timeType.trim())) {
			timeType = "yyyy-MM-dd HH:mm:ss";
		}
		return new GsonBuilder().setDateFormat(timeType).create().toJson(object);
	}

	/**
	 * json转map
	 * 多层转换。若key有相同则覆盖
	 * @param rsContent
	 * @return
	 */
	public static Map<String, String> jsonStringToMap(String rsContent) {
		Map<String, String> map = new HashMap<String, String>();
		JSONObject jsonObject = JSONObject.fromObject(rsContent);
		Iterator it = jsonObject.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next().toString();
			String value = ((Map) jsonObject).get(key).toString();
			try {
				JSONObject jo = JSONObject.fromObject(value);
				Iterator _it = jo.keySet().iterator();
				while (_it.hasNext()) {
					String _key = _it.next().toString();
					String _value = ((Map) jo).get(_key).toString();
					map.put(_key, _value);
				}
			} catch (Exception e) {
				map.put(key, value);
			}
		}
		return map;
	}
	
	/**
	 * json转map
	 * 只解析一层结构
	 * @param rsContent
	 * @return
	 */
	public static Map<String,Object> jsonToMap(String rsContent){
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		JSONObject jsonObject = JSONObject.fromObject(rsContent);
		Iterator it = jsonObject.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next().toString();
			Object value = ((Map) jsonObject).get(key);
			map.put(key, value);
		}
		return map;
	}
}
